package com.funcas.pcloud.upms.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.funcas.pcloud.common.ApiResult;
import com.funcas.pcloud.common.PageRequest;
import com.funcas.pcloud.common.base.BaseController;
import com.funcas.pcloud.upms.entity.Group;
import com.funcas.pcloud.upms.entity.User;
import com.funcas.pcloud.upms.facade.UserRestFacade;
import com.funcas.pcloud.upms.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author funcas
 * @version 1.0
 * @date 2018年10月12日
 */
@RestController
public class UserController extends BaseController implements UserRestFacade {

    private final IAccountService accountService;

    @Autowired
    public UserController(IAccountService accountService) {
        this.accountService = accountService;
    }


    @Override
    @PreAuthorize("hasAuthority('user:list')")
    public ApiResult getUserInfo(Long uid){
        User user = accountService.getUser(uid);
        return success(user);
    }

    @Override
    @PreAuthorize("hasAuthority('user:list')")
    public ApiResult getUserLists(PageRequest pageRequest, @RequestParam Map<String,Object> filter){
        IPage<User> userIPage = accountService.findUsers(pageRequest, filter);
        return success(userIPage);
    }

    @Override
    @PreAuthorize("hasAuthority('user:list')")
    public ApiResult getAllUserLists(String nickname){
        List<User> users = accountService.findUsersByNickname(nickname);
        return success(users);
    }

    @Override
    @PreAuthorize("hasAuthority('user:edit')")
    public ApiResult modifyUser(@PathVariable("userId") Long userId){
        User user = accountService.getUser(userId);
        List<Group> groupList = accountService.getUserGroups(userId);
        user.setGroup(groupList);
        return success(user);
    }

    @Override
    @PreAuthorize("hasAuthority('user:save')")
    public ApiResult saveUser(User user) {
        accountService.saveUser(user);
        return success(user);
    }

    @Override
    @PreAuthorize("hasAuthority('test')")
    public ApiResult deleteUser(@PathVariable("userId") Long userId){
        User user = accountService.getUser(userId);
        accountService.deleteUser(user);
        return success(user);
    }

}
